import { Form, Input, Select, Card, Image, message, Upload } from 'myselfantd';
import React, { useEffect, useState } from 'react';
import { addMachine, getSpuPage, getMachineInfoById, updateMachine } from '../api';
interface FormProps {
  data?: any;
  onFinish?: Function;
  handleFinish?: Function;
  viewmode?: 'view' | 'add' | 'edit';
  id?: string;
  close?: any;
}
const App: React.FC<FormProps> = ({
  viewmode = 'add',
  close,
  data,
  onFinish: handleFinish,
  id,
}) => {
  return (
    <Form.Layout
      viewmode={viewmode}
      data={async () => {
        if (id) {
          let { result } = await getMachineInfoById(id);
          return result;
        }
      }}
      formItemData={[
        [
          {
            name: 'name',
            label: '农机名称',
            rules: [{ required: true, message: '农机名称必填' }],
            render: () => <Input placeholder="请输入" />,
          },
        ],
        [
          {
            name: 'deviceSpuId',
            label: '所属品类',
            rules: [{ required: true, message: '所属品类必填' }],
            render: () => (
              <Select
                fieldNames={{ name: 'name', value: 'id' }}
                request={async () => {
                  let {
                    result: { data },
                  } = await getSpuPage({ categoryModel: 'machine', pageSize: '-1' });
                  return data;
                }}
                placeholder="请选择"
                allowClear
              />
            ),
          },
        ],
        [
          {
            name: 'code',
            label: '出厂编号',
            rules: [{ required: true, message: '出厂编号必填' }],
            render: () => <Input placeholder="请输入" />,
            editRender: () => <Input disabled placeholder="请输入" />,
          },
          {
            name: 'vin',
            label: '车架号',
            rules: [{ required: true, message: '车架号必填' }],
            render: () => <Input placeholder="请输入" />,
            editRender: () => <Input disabled placeholder="请输入" />,
          },
        ],
        [
          {
            name: 'image',
            label: '农机图片',
            render: () => <Upload urlTemplate={`${UPLOAD_IMG_URL_NEW}/hxdfs/{0}`} />,
          },
        ],
        [
          {
            name: 'note',
            label: '说 明',
            render: () => <Input.TextArea   showCount maxLength={512}/>,
          },
        ],
      ]}
      request={async (val: any) => {
        if (viewmode === 'add') {
          let res = await addMachine(val);
          if (res && res.message === 'success') {
            message.success('添加成功');
            close();
          }
        } else {
          val.id = id;
          let res = await updateMachine(val);
          if (res && res.message === 'success') {
            message.success('编辑成功');
            close();
          }
        }
      }}
      onFinish={() => {
        close();
      }}
    />
  );
};

export default App;
